#include<iostream>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<arpa/inet.h>//提供地址转换函数
int main()
{
    //1.创建监听的套接字
    int fd = socket(AF_INET,SOCK_STREAM,0);
    if(fd == -1)
    {
        perror("socket error!");
        return -1;
    }
    //2.绑定本地的IP和端口号
    struct sockaddr_in address;//声明一个sockaddr_in结构体变量address，用于存储服务器地址信息 
    address.sin_family = AF_INET;//地址族为IPV4
    address.sin_port = htons(9999);//htons用于将主机字节序转换为网络字节序
    inet_pton(AF_INET,"127.0.0.1",&address.sin_addr.s_addr);
    address.sin_addr.s_addr = INADDR_ANY;//监听所有网络接口
    int ret = connect(fd,(struct sockaddr*)&address,sizeof(address));
    if(ret == -1)
    {
        perror("connect error!");
        return -1;
    }
    int number = 0;
    //3.通信
    while(1)
    {
        //接受数据
        char buff[1024];
        sprintf(buff,"你好，hello world！%d...\n",number++);
        send(fd,buff,strlen(buff)+1,0);
        memset(buff,0,sizeof(buff));
        int len = recv(fd,buff,sizeof(buff),0);
        if(len > 0)
        {
            printf("server say : %s\n",buff);
        }
        else if(len == 0)
        {
            printf("服务器端已经断开了连接...\n");
            break;
        }
        else
        {
            perror("recv error!");
            break;
        }
        sleep(1);
    }
    //6.关闭文件描述符
    close(fd);
    return 0;
}